import {
	itemData
} from "@/utils/itemData.js";
import {
	translateZhToEn,
	translateLaosToEn,
	translateLaosToZh,
	translateZhToLaos
} from "@/utils/translate";
import {
	isEmpty
} from "@/utils/common.js";
import {
	size
} from "@/utils/size.js";

export default {
	computed: {
		itemData() {
			return itemData
		},
		size() {
			return size
		},
		user() {
			return this.$store.getters.user
		},
		site() {
			return this.$store.getters.site
		}
	},
	methods: {
		// 提交
		submit() {
			let _this = this;
			this.setCurrent()
			if (this.form.weight === 0 || this.form.freight === 0) {
				this.$refs.uToast.show({
					title: '重量或运费为0，无法提交。'
				})
				return
			}
			let data = {
				...this.form
			};
			if (this.son.hasSon) data.jsonList = JSON.stringify(this.son.childrenList) // 子单
			if (!isEmpty(this.$store.getters.order)) data.mailId = this.$store.getters.order.id // 在线下单验货
			data.freight = this.roundNumber(data.freight) // 运费向上取整
			data.courierId = this.user.id // 快递员id
			this.$refs['uForm'].validate(valid => {
				if (!valid) {
					this.$refs.uToast.show({
						title: '无法提交，有必填项未填写'
					})
					return;
				}
				uni.showModal({
					title: '确认提交？',
					content: '',
					success: function(res) {
						if (res.confirm) {
							uni.showLoading();
							_this.$api.updateCourierExpressOrderApi(data).then(result => {
								uni.hideLoading();
								if (result.status !== 200) {
									_this.$refs.uToast.show({
										title: result.message
									})
									return
								};
								// _this.print()
								_this.$refs.uToast.show({
									title: '添加成功'
								})
								_this.cancel()
							}).catch(() => {
								uni.hideLoading();
							});
						}
					}
				})
			})
		},

		// 获取一条发件人信息
		getOneSender() {
			this.$api.getSenderApi().then(result => {
				let response = result.resultParam.sender
				this.form.senderName = response.name; // 寄件人姓名
				this.translateZhToEn(response.name, 'laosSenderName', 'enSenderName'); // 寄件人姓名
				this.form.senderAddress = response.address; // 寄件人详细地址
				this.form.laosSenderAddress = ' '; // 老挝寄件人详细地址
				this.translateZhToEn(response.address, 'enSenderAddress'); // 英文寄件人详细地址
				this.form.beginPlace = response.city; // 始发地
				this.form.laosBeginPlace = ' '; // 始发地
				this.form.senderCity = response.city; // 发件人城市
				this.translateZhToEn(response.city, 'enSenderCity');
				this.form.saleCity = response.city; // 产销城市
				this.form.senderPhone = response.phone; // 寄件人联系电话
				this.form.senderId = response.idCard; // 寄件人证件号
			})
		},

		// 扫描获取单号
		scan() {
			let _this = this
			uni.scanCode({
				scanType: ['barCode'],
				success: function(res) {
					_this.form.number = res.result
					_this.getOnline()
				}
			});
		},

		// 选择物品
		confirmItem(array) {
			let extra;
			if (array[1].extra) {
				extra = array[1].extra
				this.item = array[1].value
			} else {
				extra = array[0].extra;
				this.item = array[0].value
			}
			this.filterTree(itemData, extra)
		},

		// 遍历搜索物品
		filterTree(nodes, extra) {
			return nodes.filter(node => {
				if (node.extra === extra) {
					this.changeItemName(node)
					return true
				}
				if (node.children && node.children.length) {
					node.children = this.filterTree(node.children, extra)
				}
				return true
			})
		},

		// 选择品名
		changeItemName(data) {
			this.form.articleName = '';
			this.$nextTick(() => {
				if (isEmpty(data)) {
					this.form.articleName = ''; // 品名
					this.form.laosArticleName = '';
					this.form.enArticleName = '';
					this.form.dutyParagraph = ''; // 税号
					this.form.specification = ''; // 规格
					this.form.insideCount = 0; // 内件数量
					this.form.declarationUnitFee = 0; // 申报单价
					this.form.declarationTotalFee = 0; // 申报总价
					this.form.taxRate = 0; // 税率
					this.form.receivableTax = 0; // 应收税额
					this.form.realTax = 0; // 实收税额
					this.form.repairTax = 0; // 补收税额
					this.form.detailNotes = ''; // 备注(内件明细)
					this.brand = '无品牌';
					this.brandOption = [];
					this.sizeList = [];
					return;
				}
				this.form.articleName = data.name; // 品名(中文)
				this.translateZhToLaos(data.name, 'laosArticleName') // 品名(老挝)
				this.translateZhToEn(data.name, 'enArticleName') // 品名(英文)
				this.form.dutyParagraph = data.extra; // 税号
				this.form.taxRate = this.fixed(data.tax.replace(/([0-9.]+)%/, (a, b) => +b / 100)) // 税率
				this.form.declarationUnitFee = this.fixed(data.price); // 申报单价
				this.getSpecifications(); // 规格型号
				this.$refs.SearchSelectItem.setItemMethod(data.name) // 初始化品名组件
			})
		},

		// 规格型号
		getSpecifications() {
			let number = 0;
			let sizeString = '';
			this.sizeList.forEach(item => { // 计算码数
				sizeString += `${item.name} * ${item.number}件 | `
				number += item.number
			})
			sizeString = sizeString.substring(0, sizeString.length - 3)
			if (number !== 0) { // 计算数量
				this.form.insideCount = number;
			}
			if (this.sizeList.length > 0) { // 规格型号
				this.form.specification = `${this.form.articleName} | ${this.brand} | ${sizeString}`;
			} else {
				this.form.specification =
					`${this.form.articleName} | ${this.brand} ${'| ' + this.specification + ' '} * ${this.form.insideCount}件`;
			}
			this.form.detailNotes = this.form.specification; // 备注（内件明细）
			this.form.declarationTotalFee = this.fixed(this.form.insideCount * this.form.declarationUnitFee); // 申报总价
			this.form.receivableTax = this.fixed(this.form.declarationTotalFee * this.form.taxRate); // 应收税额
		},
		changeSpecifications() {
			this.form.detailNotes = this.form.specification;
		},

		/* 计算毛重和净重 */
		changeWeight() {
			this.form.roughWeight = this.fixed(this.form.weight, 3); // 毛重KG 
			this.form.netWeight = this.fixed(this.form.weight * 0.9, 3); // 净重KG
			this.form.insideRoughWeight = this.fixed(this.form.weight, 3); // 内件毛重
		},

		/* 添加删除尺寸 */
		addSize(name) {
			let flag = this.sizeList.some(item => {
				if (item.name === name) {
					item.number++
					return true
				}
			})
			if (!flag) {
				this.sizeList.push({
					name: name,
					number: 1
				})
			}
			this.getSpecifications()
		},
		delSize(name) {
			this.sizeList.some((item, index) => {
				if (item.name === name) {
					if (item.number > 1) {
						item.number--
					} else {
						this.sizeList.splice(index, 1)
					}
				}
			})
			this.getSpecifications()
		},

		// 计算体积重量
		calculate() {
			let number = 0;
			if (this.son.childrenList.length > 0) {
				this.son.childrenList.forEach(item => {
					if (!item.length) item.length = 0;
					if (!item.width) item.width = 0;
					if (!item.height) item.height = 0;
					if (!item.count) item.count = 1;
					number += item.length * item.width * item.height * item.count
				});
			}
			if (!this.computeWeight.length) this.computeWeight.length = 0;
			if (!this.computeWeight.width) this.computeWeight.width = 0;
			if (!this.computeWeight.height) this.computeWeight.height = 0;
			let num = this.computeWeight.length * this.computeWeight.width * this.computeWeight.height;
			this.form.weight = this.fixed((num + number) / this.$volume, 1)
			this.changeWeight()
		},

		// 普通/易碎品 ---- 保额/保价费
		changeProtect() {
			if (this.form.isProtect === 0) {
				this.form.protectWay = 0;
				this.form.coverage = 0;
				this.form.protectFee = 0;
				return
			}
			if (this.form.protectWay === 1) {
				this.form.protectFee = this.fixed(this.form.coverage * 0.3)
			}
			if (this.form.protectWay === 0) {
				this.form.protectFee = this.fixed(this.form.coverage * 0.03)
			}
		},

		// 报关费
		changeIsCustoms(value) {
			if (value === 0) this.form.customsFee = 0;
		},

		// 获得所有网点
		getAllSite() {
			let data = {
				username: ''
			}
			this.$api.listAllUserApi(data).then(result => {
				this.sendSite = result.resultParam.userList
			})
		},
		// 选择发往网点
		selectSend(index) {
			let obj = this.sendSite[index]
			this.form.sendToUserId = obj.id
			this.form.sendToName = obj.name
			this.form.laosSendToName = obj.laosName
			this.form.sendToUserName = obj.username
		},

		// 翻译 中 -> 英
		translateZhToEn(query, ...argument) {
			if (!query) return
			translateZhToEn(query).then(result => {
				argument.forEach(key => {
					if (Object.prototype.hasOwnProperty.call(this.form, key))
						this.form[key] = result
				})
			})
		},
		// 翻译 中 -> 老
		translateZhToLaos(query, ...argument) {
			if (!query) return
			translateZhToLaos(query).then(result => {
				argument.forEach(key => {
					if (Object.prototype.hasOwnProperty.call(this.form, key))
						this.form[key] = result
				})
			})
		},
		// 翻译 老 -> 中
		translateLaosToZh(query, ...argument) {
			if (!query) return
			translateLaosToZh(query).then(result => {
				argument.forEach(key => {
					if (Object.prototype.hasOwnProperty.call(this.form, key))
						this.form[key] = result
				})
			})
		},
		// 翻译 老 -> 英
		translateLaosToEn(query, ...argument) {
			if (!query) return
			translateLaosToEn(query).then(result => {
				argument.forEach(key => {
					if (Object.prototype.hasOwnProperty.call(this.form, key))
						this.form[key] = result
				})
			})
		},
		// 翻译 老 -> 中 英
		translateZhAndEn() {
			this.translateLaosToZh(this.form.laosArticleName, 'articleName')
			this.translateLaosToEn(this.form.laosArticleName, 'enArticleName')
		},

		// 向上取整1000
		roundNumber(num) {
			const number = 1000
			if (num >= number) {
				let temp = num % number; // 取余
				if (temp !== 0) {
					num = num - temp + number
				}
			} else {
				num = number;
			}
			return num
		},

		// 保留小数
		fixed(num, digit = 2) {
			num = num / 1
			num = num.toFixed(digit) / 1
			return num
		}
	}
}
